<template>
  <div class="login-content">
    <div class="login-main">
      <div class="login-logo">
        <div class="login-logo-bg"></div>
        <span>实验室信息管理系统</span>
      </div>
      <div class="loginForm">
        <div class="formHeader">欢迎使用</div>
        <div class="formContent">
          <form autocomplete="off" @click.stop @keyup.enter="throttledLogin">
            <div class="login-form-item">
              <van-icon name="cluster-o" />
              <input
                type="text"
                placeholder="域名"
                v-model="domain"
                @blur="handleBlur" />
              <van-icon name="replay" @click.stop="resetDomain" />
            </div>
            <div class="login-form-item">
              <van-icon name="user-o" />
              <input
                type="text"
                placeholder="账号"
                v-model="loginForm.username"
                autocomplete="new-password" />
              <van-icon name="arrow-down" @click.stop="showSheet = true" />
            </div>
            <div class="login-form-item">
              <van-icon name="lock" />
              <input
                :type="pwdType ? 'password' : 'text'"
                placeholder="密码"
                v-model="loginForm.password"
                autocomplete="new-password" />
              <van-icon
                :name="pwdType ? 'closed-eye' : 'eye-o'"
                @click.stop="pwdType = !pwdType" />
            </div>
          </form>
        </div>
        <van-button
          size="large"
          @click.stop="throttledLogin"
          :loading="loading"
          loading-text="登录中..."
          loading-type="spinner"
          :disabled="!loginForm.username || !loginForm.password"
          >登录</van-button
        >
      </div>
    </div>
    <p class="login-copyright">杭州先腾数据技术有限公司</p>
    <!-- <van-action-sheet title="历史账号" v-model="showSheet" /> -->
  </div>
</template>

<script>
import tokenValidate from '@/utils/tokenValidate'
import { GetApkVersion } from "@/api/base";
import { GetEmpowerUserIDs, login } from "@/api/user";
import {
  getDomain,
  setDomain,
  setLoginlogid,
  setRoles,
  setToken,
  setUsercode,
  setUsername,
} from "@/utils/auth";
import { throttle } from "lodash";
import { ActionSheet, Button, Dialog, Icon, Notify } from "vant";
export default {
  name: "Login",
  components: {
    [Icon.name]: Icon,
    [Button.name]: Button,
    [ActionSheet.name]: ActionSheet,
    [Notify.name]: Notify,
    [Dialog.name]: Dialog,
  },
  data() {
    let usernames;
    let username = "";
    return {
      loginForm: {
        username,
        password: "",
      },
      domain: getDomain().replace("http://", ""),
      loading: false,
      redirect: undefined,
      otherQuery: {},
      pwdType: true,
      showSheet: false,
      usernames,
    };
  },
  computed: {},
  watch: {},
  methods: {
    handleBlur() {
      this.getUpdataApk();
    },
    resetDomain() {
      this.domain = process.env.VUE_APP_BASE_API.replace("http://", "");
    },
    Login() {
      var _this = this;
      setDomain(`http://${this.domain}`);
      var result = {
        queryModel: {
          Code: this.loginForm.username,
        },
      };
      GetEmpowerUserIDs(result)
        .then((response) => {
          if (response.Result == null || response.Result.length == 0) {
            var sourceUserID = _this.loginForm.username;
            _this.handleLogin(sourceUserID);
          }
        })
        .catch(() => {});
    },
    handleLogin(val) {
      var that = this;
      this.loading = true;
      var _this = this;
      var param = {
        UserName: "",
        Pwd: "",
      };
      param.UserName = this.loginForm.username;
      param.Pwd = this.loginForm.password;
      var newParam = btoa(encodeURI(JSON.stringify(param)));
      var httpDomain = "http://" + this.domain;
      var newParam = { user: newParam };
      login(newParam)
        .then((response) => {
          const { Result } = response;
          this.loading = false;
          if (response.ErrorCode == 0) {
            var token = Result.Token;
            var loginlogid = Result.loginlogid;
            var role = Result.data.pages;
            setToken(Result.Token);
            setRoles(Result.data);
            setUsername(Result.UserName);
            setUsercode(Result.UserID);
            setLoginlogid(Result.loginlogid);
            localStorage.setItem("tokenKey", token);
            localStorage.setItem("domainKey", httpDomain);
            localStorage.setItem("loginlogidKey", loginlogid);
            localStorage.setItem("roles", JSON.stringify(role));
            
            const validate = new tokenValidate();
            validate.start();
            setTimeout(function () {
              _this.$router.push({
                name: "home",
              });
            }, 500);
          }
        })
        .catch(() => {
          that.loading = false;
        });
    },
    getUpdataApk() {
      let that = this;
      // var widgetInfo = {
      //   version: "1.0.1",
      // };
      if (process.env.NODE_ENV === "production") {
        document.addEventListener("plusready", function () {
          plus.runtime.getProperty(plus.runtime.appid, function (widgetInfo) {
            let currentVersion = "";
            if (widgetInfo.version) {
              currentVersion = widgetInfo.version.replace(/\./g, "");
            }
            GetApkVersion()
              .then((response) => {
                var newVersion = "";
                if (response.Result.version) {
                  newVersion = response.Result.version.replace(/\./g, "");
                }
                if (Number(newVersion) > Number(currentVersion)) {
                  Dialog({
                    title: "提示",
                    message: "APP存在新版本，是否更新？",
                  }).then(async () => {
                    plus.runtime.openURL(
                      `http://${that.domain}${response.Result.path}`
                    );
                  });
                }
              })
              .catch(() => {});
          });
        });
      }
    },
  },
  beforeCreate() {},
  created() {
    this.getUpdataApk();
    this.throttledLogin = throttle(this.Login, 500, {
      leading: true,
      trailing: false,
    }); //节流，确保函数0.5秒内只执行一次
  },
  mounted() {
    if (typeof window.plus !== "undefined") {
      this.plusReady();
    } else {
      document.addEventListener("plusready", this.plusReady);
    }
    localStorage.removeItem("showMessage");
  },
  beforeDestroy() {},
  destroyed() {},
};
</script>

<style>
html.login-hack,
html.login-hack body,
html.login-hack #app {
  height: 100%;
  overflow-y: hidden;
}
</style>

<style lang="scss" scoped>
$white: #fff;
$blue: #87cbff;
$box-sizing: border-box;
$font-size: 14px;

@mixin flex-column-base($justify) {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: $justify;
}

* {
  box-sizing: $box-sizing;
}

.login-content {
  height: 100%;
  color: $white;
  font-size: $font-size;
  width: 100%;
  position: relative;
  background-image: url("../../assets/login_bg.jpg");
  background-size: 100% 100%;
  .login-main {
    height: 100%;
    width: 100%;
    @include flex-column-base(center);
    position: relative;
    .login-logo {
      font-size: 22px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40%;
      text-align: center;
      position: absolute;
      left: 30%;
      top: 15%;
      span {
        letter-spacing: 1px;
        color: #fff;
        margin-bottom: 2px;
        font-family: "楷体", "KaiTi", serif;
      }
      .login-logo-bg {
        width: 0.6rem;
        height: 0.6rem;
        background-image: url("../../assets/logo.png");
        background-size: 75% 75%;
        background-repeat: no-repeat;
        background-position: center;
        background-color: $white;
        border-radius: 5px;
        margin-right: 5px;
      }
    }
    .loginForm {
      width: 40%;
      height: 60%;
      position: absolute;
      top: 25%;
      left: 30%;
      background: #fff;
      border-radius: 5px;
      color: #388ff0;
      @include flex-column-base(space-around);
    }
    form {
      width: 100%;
      display: flex;
      justify-content: space-around;
      flex-direction: column;
      height: 100%;
      .login-form-item {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #388ff0;
        height: 32px;
        padding: 0 5px;
        input {
          display: block;
          flex: 1;
          background: transparent;
          border: none;
          outline: none;
          &::placeholder {
            color: $white;
          }
        }
        .van-icon {
          display: block;
          width: 22px;
        }
      }
    }
    .formContent {
      height: 50%;
    }
    .van-button {
      font-size: $font-size;
      letter-spacing: 2px;
      width: 80%;
      height: 30px;
      background: #388ff0;
      color: #fff;
      border-radius: 5px;
    }
  }
  .login-copyright {
    position: absolute;
    margin: 0;
    left: 0;
    bottom: 20px;
    display: block;
    text-align: center;
    width: 100%;
    font-size: 12px;
    color: #fff;
    // position: relative;
    // bottom: -45px;
  }
}
</style>
